package com.support.widget.util;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES+Base64加密和解密
 * @author Administrator
 *
 */
public class EncryptionUtil {

	// AES秘钥
	public static final String IV = "L+\\~f4,Ir)b$=pkf";
	public static final String KEY1 = "abcdef1234567890";
	public static final String KEY2 = "s6vSeN6IEi5fM4OJySXoPuqsofEc0zqITj9T8RFwXDU=";

	public static String encrypt(String content) throws Exception {

		String temp = EncryptionUtil.desEncrypt(KEY1, KEY2);
		byte bt[] = Base64.decode(temp, Base64.DEFAULT);
		String data = new String(bt, "UTF-8");
		String realkey = EncryptionUtil.desEncrypt(KEY1, data);
		String miwen = EncryptionUtil.encrypt(realkey, content);
		return miwen;

	}

	public static String descrypt(String content) throws Exception {
		String temp = EncryptionUtil.desEncrypt(KEY1, KEY2);
		byte bt[] = Base64.decode(temp, Base64.DEFAULT);
		String data = new String(bt, "UTF-8");
		String realkey = EncryptionUtil.desEncrypt(KEY1, data);
		String miwen = EncryptionUtil.desEncrypt(realkey, content);
		String hack = miwen.trim();
		return hack;
	}

	/**
	 * 加密
	 * @param key1
	 * @param value
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String key1, String value) throws Exception {
		try {
			String data = value;
			String key = key1;
			String iv = IV;

			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			int blockSize = cipher.getBlockSize();

			byte[] dataBytes = data.getBytes();
			int plaintextLength = dataBytes.length;
			if (plaintextLength % blockSize != 0) {
				plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
			}

			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

			cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
			byte[] encrypted = cipher.doFinal(plaintext);
			return Base64.encodeToString(encrypted, Base64.DEFAULT);

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 *  真实的密钥（key3）=Aes解密（Base64解密( Aes解密(key1，key2) )，key1）
	 * @param key
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String desEncrypt(String key, String data) throws Exception {
		try {
			String iv = IV;// 加密向量
			byte[] encrypted1 = Base64.decode(data, Base64.DEFAULT);
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original);
			return originalString;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
